package com.g8.pethospitallearnbackend.service.impls;

import com.g8.pethospitallearnbackend.entity.Casefields;
import com.g8.pethospitallearnbackend.entity.Learnprocess;
import com.g8.pethospitallearnbackend.exception.CustomException;
import com.g8.pethospitallearnbackend.mapper.CaseMapper;
import com.g8.pethospitallearnbackend.mapper.CasefieldsMapper;
import com.g8.pethospitallearnbackend.mapper.LearnprocessMapper;
import com.g8.pethospitallearnbackend.service.CasefieldsService;
import com.g8.pethospitallearnbackend.utils.responseUtil.ResponseStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Case;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class CasefieldsServiceImpl implements CasefieldsService {
    @Autowired
    private CasefieldsMapper casefieldsMapper;
    @Autowired
    private CaseMapper caseMapper;
    @Autowired
    private LearnprocessMapper learnprocessMapper;

    @Override
    public List<Casefields> getAllFields() {
        List<Casefields> casefields=casefieldsMapper.selectAllIdFirst();
        if(casefields==null || casefields.isEmpty()){
            throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST,"病例模板中没有字段");
        }
        return casefields;
    }

    /**
     * 通过英文字段名改中文字段名
     * @param modifiedFields
     * @return
     */
    @Override
    public List<String> modifyCasefieldByEnAttr(List<Casefields> modifiedFields) {
        List<String> modifiedCaseFields=new ArrayList<>();
        for(Casefields casefields:modifiedFields){
            if(casefields.getChAttr().isBlank()||casefields.getChAttr().isEmpty()) throw new CustomException(ResponseStatusEnum.BAD_REQUEST,"chAttr不能为空");
            int code=casefieldsMapper.updateByPrimaryKey(casefields);
            if(code!=1) throw new CustomException(ResponseStatusEnum.BAD_REQUEST,"修改失败，"+casefields.getEnAttr()+"不存在");
            else{
                modifiedCaseFields.add(casefields.getEnAttr());
            }
        }
        return modifiedCaseFields;
    }

    /**
     * 添加字段：暂时用预留字段实现
     * 1.在casefield表中找到chAttr还是null的即可用字段
     * 2.case表结构不用改，但是前端显示的时候必须先拿casefield知道哪些是在真正的病例模板中的
     * @param chAttr
     * @return
     */
    @Override
    public String addCasefield(String chAttr) {
        List<String> usableEnAttr=casefieldsMapper.selectNULLEnAttr();//可以使用的default字段
        //判断是否还有可用的字段
        if(usableEnAttr==null||usableEnAttr.isEmpty())
            throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR,"系统错误：没有可用字段");
        //把casefield中chAttr为NULL的改成中文字段,所以这里实际上是update不是insert，接下来随便挑选一个是null的字段给它的chAttr字段填入前端传的中文
        String usable=usableEnAttr.get(0);
        Casefields addedFields=new Casefields(
                usable,
                chAttr
        );
        //chAttr不能和已有的重复
        try {
            int code=casefieldsMapper.updateByPrimaryKey(addedFields);
            if(code!=1) throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR,"增添字段失败");
        }catch (DuplicateKeyException e){
            throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR,chAttr+"已存在");
        }

        //TODO:修改表结构，使用工具pt-online-schema-change

        return chAttr+"添加成功";
    }

    /**
     * 获得所有英文字段
     * @return
     */
    @Override
    public List<String> getEnFields() {
        List<Casefields> casefields=getAllFields();
        List<String> enfields=new ArrayList<>();
        for(Casefields casefield:casefields){
            enfields.add(casefield.getEnAttr());
        }
        if(enfields==null||enfields.isEmpty()){
            throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST,"病例模板没有字段");
        }
        return enfields;
    }

    /**
     * 删除字段，暂时用预留字段实现
     * 将casefields表中原来chAttr为所给参数的设为null，本质上也是update
     * @param chAttr
     * @return
     */
    @Override
    public String deleteCasefield(String chAttr) {
        //找到目前所有的chAttr，不知道null会怎么处理
        List<String> existedChAttr=casefieldsMapper.selectChAttr();
        if(existedChAttr.contains(chAttr)){
            //说明是存在的，可以删除，即改为null
            //找到对应的enAttr，确保chAttr是唯一的那么enAttr也是唯一的
            String enAttr=casefieldsMapper.selectEnAttrByChAttr(chAttr);
            log.error("英文字段"+enAttr);
            List<String> modules=learnprocessMapper.selectAllModulesUsed();
            for(String str:modules){
                if(str.contains(enAttr)){
                    throw new CustomException(ResponseStatusEnum.NO_ACCESS,"该字段被学习流程引用，无法删除！");
                }
            }
            Casefields tobeDeleted=new Casefields(enAttr,null);

            //another problem:对应的enAttr字段要全部设为NULL，不然下一次有可能还是上一个模板的数据
            casefieldsMapper.updateTableSetNull(enAttr);

            int code=casefieldsMapper.updateByPrimaryKey(tobeDeleted);
            log.error("更新:"+code);
            if(code!=1) throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR,"删除"+chAttr+"失败");
        }
        else{
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST,"不存在该字段"+chAttr);
        }
        return chAttr+"已删除";
    }
}
